//
//  HomeViewController.swift
//  PhotoBrowser
//
//  Created by haoran on 16/4/27.
//  Copyright © 2016年 xuhaoran. All rights reserved.
//

import UIKit

private let reuseIdentifier = "HomeCell"

class HomeViewController: UICollectionViewController {

    // MARK:- 定义属性
    private lazy var shops : [Shop] = [Shop]()
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1.请求数据
        loadData(0)
    }
 
}


//MARK:- 自定义函数
extension HomeViewController {
    func showPhotoBrowser(indexPath :NSIndexPath)  {
        // 1.创建大图控制器
        let photoBrowserVC = PhotoBrowserViewController()
        
        // 2.给photoBrowserVC设置属性
        photoBrowserVC.shopArray = shops
        photoBrowserVC.indexPath = indexPath
        
        
        // 弹出大图控制器
        self.presentViewController(photoBrowserVC, animated: true, completion: nil)
    }
}


// MARK:- 数据请求
extension HomeViewController {
    /// 加载数据
    private func loadData(offset : Int) {
        NetworkTools.shareInstance.loadHomeData(offset) { (response, error) in
            
            // 1.错误校验
            if error != nil {
                print(error)
                return
            }
            
            // 2.获取返回信息
            guard let responseArray = response else {
                print("结果不正确")
                return
            }
            
            // 3.判断是否有数据
            for responseDict in responseArray{
                let shop = Shop(dict:responseDict)
                self.shops.append(shop)
            }
            
            // 4.展示数据
            self.collectionView?.reloadData()
            
        }
    }
}






// MARK:- collectionView数据源和代理方法
extension HomeViewController {

    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.shops.count
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        // 1.创建cell
        let cell = collectionView .dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HomeCell
        
        // 2.设置数据
        cell.shop = self.shops[indexPath.item]

        // 3.判断是否是最后一个cell出现在屏幕
        if indexPath.item == self.shops.count - 1 {
            self.loadData(self.shops.count)
        }
        
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        showPhotoBrowser(indexPath)
        
    }
    
    
}